class BlockingQueue {
    private String[] elems = null;
    private int head = 0;
    private int end = 0;
    private int size = 0;
    private Object locker = new Object();

    public BlockingQueue(int capability) {
        elems = new String[capability];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while (size >= elems.length) {
                locker.wait();
                //让代码阻塞
            }

            elems[end] = elem;
            end++;
            if (end >= elems.length) {
                end = 0;
            }
            size++;
            locker.notify();
        }
    }
    public String take() throws InterruptedException {
        String elem = null;
        synchronized (locker) {
            while (size == 0) {
                //让代码阻塞
                locker.wait();
            }
            elem = elems[head];
            head++;
            if (head >= elems.length) {
                head = 0;
            }
            size--;
            //出队列成功时进行唤醒
            locker.notify();
        }
        return elem;
    }

}
public class TestDemo1 {
    public static void main(String[] args) {
        BlockingQueue blockingQueue = new BlockingQueue(1000);
        Thread t1 = new Thread(() -> {
            int n =1;
            while(true) {
                try {
                    blockingQueue.put(n + "");
                    System.out.println("生产元素" + n);
                    n ++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while(true) {
                try {
                    String n = blockingQueue.take();
                    System.out.println("消费元素" + n);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}
